package com.ukao.cashregister.retrofit;


import com.ukao.cashregister.utils.T;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;


public abstract class ApiCallback<M> extends Subscriber<M> {
    private static final String SOCKETTIMEOUTEXCEPTION = "网络连接超时，请检查您的网络状态，稍后重试";
    private static final String CONNECTEXCEPTION = "网络连接异常，请检查您的网络状态";
    private static final String UNKNOWNHOSTEXCEPTION = "网络异常，请检查您的网络状态";
    private static final String CHECKUNKNOWNHOSTEXCEPTION = "网络连接失败，请检查您的网络状态";
    public abstract void onSuccess(M model);

  //  public abstract void onFailure(String msg);

    public abstract void onFinish();


    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            //httpException.response().errorBody().string()
            int code = httpException.code();
            String msg = httpException.getMessage();
            onFinish();
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
                T.show(msg);
            }

        } else {

            onFinish();
            if (e instanceof SocketTimeoutException) {
                T.show(SOCKETTIMEOUTEXCEPTION);
            } else if (e instanceof ConnectException) {
                T.show(CONNECTEXCEPTION);
            } else if (e instanceof UnknownHostException) {
                T.show(UNKNOWNHOSTEXCEPTION);
            }else if (e instanceof SocketException) {
                T.show(CHECKUNKNOWNHOSTEXCEPTION);
            }



        }

    }


    @Override
    public void onNext(M model) {

        onSuccess(model);

    }

    @Override
    public void onCompleted() {
        onFinish();
    }
}
